

import 'dart:async';

import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';
import 'package:chatgreat/helper/platform.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:in_app_purchase/in_app_purchase.dart';

import '../page/component/dialog.dart';
import '../repo/api_server.dart';
import 'helper.dart';

class PurchasePay {
  StreamSubscription<List<PurchaseDetails>>? _subscription;
  var paymenting = false; // 点击按钮支付流程启动中
  BuildContext? context;
  var type = 1;

  void Function(PurchaseStatus status)? onPurchaseStatusEvent;
  void Function()? onClosePaymentLoadingEvent;

  PurchasePay._();

  static PurchasePay? _manager;

  factory PurchasePay() {
    if (_manager == null) {
      _manager = PurchasePay._();
      _manager!.initPurchase();
    }
    return _manager!;
  }

  initPurchase() async {
    if (PlatformTool.isIOS()) {
      final purchaseUpdated = InAppPurchase.instance.purchaseStream;
      _subscription = purchaseUpdated.listen((purchaseDetailsList) async {
        if (paymenting) {
          _listenToPurchaseUpdated(purchaseDetailsList);
        } else {
          for (var purchaseDetails in purchaseDetailsList) {
            // if (purchaseDetails.pendingCompletePurchase) {
            print('---------------------> ${purchaseDetails.purchaseID}');
            await InAppPurchase.instance.completePurchase(purchaseDetails);
            // }
          }
        }
      }, onDone: () {
        _subscription?.cancel();
        _subscription = null;
      }, onError: (error) {
        showErrorMessage(error.toString());
      });
    }
  }

  stopPurchase() {
    _subscription?.cancel();
    _subscription = null;
  }

  /// 监听支付状态
  void _listenToPurchaseUpdated(
      List<PurchaseDetails> purchaseDetailsList,
      ) async {
    for (var purchaseDetails in purchaseDetailsList) {
      print('---------------------> ${purchaseDetails.purchaseID}');

      if (purchaseDetails.status == PurchaseStatus.pending) {
        print('============> 等待支付');
      } else {
        switch (purchaseDetails.status) {
          case PurchaseStatus.error:
            print('============> 支付错误');
            if (onClosePaymentLoadingEvent != null) {
              onClosePaymentLoadingEvent!();
            }
            if (context != null) {
              showErrorMessage(resolveError(context!, purchaseDetails.error!));
            }
            break;
          case PurchaseStatus.purchased: // fall through
            if (paymenting) {
              paymenting = false;
            }
            // 执行你的逻辑
            print('============> 购买成功');
            APIServer().verifyApplePay(purchaseDetails.verificationData.serverVerificationData, type: type).then((code) {
              if (onClosePaymentLoadingEvent != null) {
                onClosePaymentLoadingEvent!();
              }
              showSuccessMessage('购买成功');
            }).onError((error, stackTrace) {
              if (onClosePaymentLoadingEvent != null) {
                onClosePaymentLoadingEvent!();
              }
              if (context != null) {
                showErrorMessage(resolveError(context!, purchaseDetails.error!));
              }
            });
            break;
          case PurchaseStatus.restored:
            APIServer().verifyApplePay(purchaseDetails.verificationData.serverVerificationData, type: type).then((code) {
              if (onClosePaymentLoadingEvent != null) {
                onClosePaymentLoadingEvent!();
              }
              showSuccessMessage('恢复成功');
            }).onError((error, stackTrace) {
              if (onClosePaymentLoadingEvent != null) {
                onClosePaymentLoadingEvent!();
              }
              if (context != null) {
                showErrorMessage(resolveError(context!, purchaseDetails.error!));
              }
            });
            break;
          case PurchaseStatus.canceled:
            // _closePaymentLoading();
            if (onClosePaymentLoadingEvent != null) {
              onClosePaymentLoadingEvent!();
            }
            showErrorMessage('购买已取消');
            break;
          case PurchaseStatus.pending:
          // TODO: Handle this case.
        }

        if (purchaseDetails.pendingCompletePurchase) {
          await InAppPurchase.instance.completePurchase(purchaseDetails);
        }
      }
    }
  }

  Future<void> clearPendingPurchases() async {
    try {
      final transactions = await SKPaymentQueueWrapper().transactions();
      for (final transaction in transactions) {
        try {
          await SKPaymentQueueWrapper().finishTransaction(transaction);
        } catch (e) {
          debugPrint("Error clearing pending purchases::in::loop");
          debugPrint(e.toString());
          rethrow;
        }
      }
    } catch (e) {
      debugPrint("Error clearing pending purchases");
      debugPrint(e.toString());
      rethrow;
    }
  }
}